<template>
  <div class="vector-container"  v-loading="loading">
    <el-card>
      <template #header>
        <div class="header">
          <span>向量库列表</span>
          <el-button type="primary" @click="handleAdd">添加向量库</el-button>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="唯一键" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="supplier" label="类型">
          <template #default="{ row }">
            <el-tag :type="getSupplierTagType(row.supplier)">
              {{ row.supplier }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="host" label="主机" />
        <el-table-column prop="port" label="端口" />
        <el-table-column prop="userName" label="用户名" />
        <el-table-column prop="dataBase" label="数据库名" />
        <el-table-column prop="tableName" label="表名" />
        <el-table-column prop="dimensions" label="向量维度" />
        <el-table-column prop="ctime" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
        <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

   

    <!-- 添加/编辑向量库对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="唯一键" prop="code">
          <el-input v-model="form.code" placeholder="请输入唯一键" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="类型" prop="supplier">
          <el-select v-model="form.supplier" placeholder="请选择类型">
            <el-option label="PG" value="PG" />
            <el-option label="Milvus" value="MILVUS" />
            <el-option label="Elasticsearch" value="ES" />
          </el-select>
        </el-form-item>
        <el-form-item label="主机" prop="host">
          <el-input v-model="form.host" placeholder="请输入主机地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input-number v-model="form.port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="数据库名" prop="database">
          <el-input v-model="form.database" placeholder="请输入数据库名" />
        </el-form-item>
        <el-form-item label="表名" prop="tableName">
          <el-input v-model="form.tableName" placeholder="请输入表名" />
        </el-form-item>
        <el-form-item label="向量维度" prop="dimensions">
          <el-input-number v-model="form.dimensions" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '../../composables/useCommon'

// 表格数据
const tableData = ref([])
// 表格 loading 状态
const loading = ref(false)
// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    const res = await request('ragEmbeddingStore/', 'get', {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      name: searchQuery.value
    })
    tableData.value = res.records
    total.value = res.total
  } catch (err) {
    ElMessage.error('获取向量库列表失败')
  } finally {
    loading.value = false
  }
}

// 新增向量库
const addVectorStore = async (vectorData) => {
  try {
    await request('ragEmbeddingStore/', 'post', vectorData)
    ElMessage.success('向量库添加成功')
    getTableData()
  } catch (err) {
    ElMessage.error('添加向量库失败')
  }
}

// 修改向量库
const updateVectorStore = async (vectorData) => {
  try {
    await request('ragEmbeddingStore/', 'put', vectorData)
    ElMessage.success('向量库更新成功')
    getTableData()
  } catch (err) {
    ElMessage.error('更新向量库失败')
  }
}

// 删除向量库
const deleteVectorStore = async (vectorId) => {
  try {
    await request(`ragEmbeddingStore/${vectorId}`, 'delete')
    ElMessage.success('向量库删除成功')
    getTableData()
  } catch (err) {
    ElMessage.error('删除向量库失败')
  }
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加向量库')
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: '',
  code: '',
  name: '',
  supplier: 'PG',
  host: '',
  port: null,
  userName: '',
  password: '',
  database: '',
  tableName: '',
  dimensions: null
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入唯一键', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  supplier: [{ required: true, message: '请选择类型', trigger: 'change' }],
  host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口号', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  database: [{ required: true, message: '请输入数据库名', trigger: 'blur' }],
  tableName: [{ required: true, message: '请输入表名', trigger: 'blur' }],
  dimensions: [{ required: true, message: '请输入向量维度', trigger: 'blur' }]
}

// 处理添加向量库
const handleAdd = () => {
  dialogTitle.value = '添加向量库'
  Object.keys(form).forEach(key => (form[key] = ''))
  dialogVisible.value = true
}

// 处理编辑向量库
const handleEdit = (row) => {
  dialogTitle.value = '编辑向量库'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 处理删除向量库
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认要删除该向量库吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await deleteVectorStore(row.id)
    } catch (err) {
      ElMessage.error('删除失败')
    }
  })
}

// 处理表单提交
const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (form.id) {
        updateVectorStore(form)
      } else {
        addVectorStore(form)
      }
      dialogVisible.value = false
    }
  })
}

// 获取厂商标签样式
const getSupplierTagType = (supplier) => {
  switch (supplier) {
    case 'PG':
      return 'success'
    case 'MILVUS':
      return 'warning'
    case 'ES':
      return 'danger'
    default:
      return 'info'
  }
}

// 搜索
const searchQuery = ref('')
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

// 获取表格数据
getTableData()
</script>

<style scoped>
.vector-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

</style>
